var express = require('express');
var router = express.Router();
var OrderDao = require('../models/Order');
var Users = require('../models/Users').Users;
/*var jwt = require('express-jwt');
//var tokenManager = require('../utils/token_manager');
var secret = require('../utils/secret');
var luosimao = require("../utils/luosimao");*/
var randomString = require('random-string');//获取随机6位数字
var request = require('request');
var gm = require('gm');//处理图片
var fs = require('fs');
/* GET users listing. */

router.post('/login', function(req, res) {//用户登录
  new Users().findUser(req.body.username,req.body.password,1,function(result){
      if(result==401){
          res.send(401);
      }else{
          res.json(result);
      }

  });
});


router.post('/resetPass', function(req, res) {//重置密码

  new Users().resetPass(req.body.username,req.body.password,function(result){
      res.send(result);
  });

});
router.post('/register', function(req, res) {//用户注册
    new Users(req.body.username,null,null,null,null,null,req.body.password,req.body.type,new Date(),0,0,null,null,null,null,null,0,0,0,0,null,null,req.body.username).saveUser(function(result){
        res.send(result);
    });
});

router.post('/getCode', function(req,res){
    var randomNum = randomString({
        length: 6,
        numeric: true,
        letters: false,
        special: false
    });

    var phone = req.body.username;
    var type = req.body.type;

        new Users().checkUser(req.body.username,function(result){
            if(type=='resetPass') {//如果是重置密码先查询手机号是否存在
                if(result=='hasUser'){
                    //luosimao.sms(phone,'您正在重置账号密码,验证码为：'+randomNum+'【运车管家】');
                    request.post({url:'http://222.73.117.158:80/msg/HttpBatchSendSM',
                        form: {account:'vip_ycgj',pswd:'Tch123456',mobile:phone,msg:'您正在重置账号密码,验证码为：'+randomNum,needstatus:true}},
                        function optionalCallback(err, httpResponse, body) {
                        /*if (err) {
                            //return console.error('upload failed:', err);
                           return res.send('err');
                        }else{
                            var ss = body.split('\n')[0];
                            if(ss.substring(ss.indexOf(',')+1,ss.length)!=0){
                                return res.send('err');
                            }
                        }*/
                    });

                }else{
                    randomNum='nouser';
                }

            }else if(type=='register'){
                if(result!='hasUser'){//证明手机号未被注册
                    //luosimao.sms(phone,'您正在注册新账户,验证码为：'+randomNum+'【运车管家】');
                    request.post({url:'http://222.73.117.158:80/msg/HttpBatchSendSM',
                            form: {account:'vip_ycgj',pswd:'Tch123456',mobile:phone,msg:'您正在注册新账户,验证码为：'+randomNum,needstatus:true}},
                        function optionalCallback(err, httpResponse, body) {

                        });

                }else{
                    randomNum='hasuser';
                }
                //res.send(randomNum);
            }else if(type=='sendold'){
                if(result=='hasUser'){//证明手机号未被注册
                    //luosimao.sms(phone,'您正在注册新账户,验证码为：'+randomNum+'【运车管家】');
                    request.post({url:'http://222.73.117.158:80/msg/HttpBatchSendSM',
                            form: {account:'vip_ycgj',pswd:'Tch123456',mobile:phone,msg:'您正在修改账户手机号码,验证码为：'+randomNum,needstatus:true}},
                        function optionalCallback(err, httpResponse, body) {

                        });

                }else{
                    randomNum='nouser';
                }
            }else if(type=='modifyphone'){
                if(result!='hasUser'){//证明手机号未被注册
                    //luosimao.sms(phone,'您正在注册新账户,验证码为：'+randomNum+'【运车管家】');
                    request.post({url:'http://222.73.117.158:80/msg/HttpBatchSendSM',
                            form: {account:'vip_ycgj',pswd:'Tch123456',mobile:phone,msg:'您正在绑定此手机号码,验证码为：'+randomNum,needstatus:true}},
                        function optionalCallback(err, httpResponse, body) {

                        });

                }else{
                    randomNum='hasuser';
                }
            }else if(type=='phoneCode'){
                request.post({url:'http://222.73.117.158:80/msg/HttpBatchSendSM',
                        form: {account:'vip_ycgj',pswd:'Tch123456',mobile:phone,msg:'您正在验证手机号码,验证码为：'+randomNum,needstatus:true}},
                    function optionalCallback(err, httpResponse, body) {
                        console.log(randomNum);
                    });
            }else if(type==''){}
            res.send(randomNum);

        });


});
router.post('/Accept',function(req,res){
    console.log(req.body.phone+"========="+req.body.name);
    var phone=req.body.phone;
        if(req.body.name){
            request.post({url:'http://222.73.117.158:80/msg/HttpBatchSendSM',
                    form: {account:'vip_ycgj',pswd:'Tch123456',mobile:phone,msg:'亲，恭喜您，'+req.body.name+'已经接受了您的报价，请进入 http://c.iyunche.cn/ 查看发车人联系方式。'
                        ,needstatus:true}},
                function optionalCallback(err, httpResponse, body) {
                    res.send(true);
                }
            );
        }else{
            request.post({url:'http://222.73.117.158:80/msg/HttpBatchSendSM',
                    form: {account:'vip_ycgj',pswd:'Tch123456',mobile:phone,msg:'亲，恭喜您，'+req.body.myphone+'已经接受了您的报价，请进入 http://c.iyunche.cn/ 查看发车人联系方式。'
                        ,needstatus:true}},
                function optionalCallback(err, httpResponse, body) {
                    res.send(true);
                }
            );
        }
});
router.post('/Bid',function(req,res){
    var phone=req.body.phone;
    var price=req.body.price;
    if(req.body.company){
        request.post({url:'http://222.73.117.158:80/msg/HttpBatchSendSM',
                form: {account:'vip_ycgj',pswd:'Tch123456',mobile:phone,msg:'亲，我们很高兴地通知您，'+req.body.company+'给您的发车单报价'+price+'元，如果满意，请进入 http://www.iyunche.cn 接受报价。'
                    ,needstatus:true}},
            function optionalCallback(err, httpResponse, body) {
                res.send(true);
            }
        );
    }else{
        request.post({url:'http://222.73.117.158:80/msg/HttpBatchSendSM',
                form: {account:'vip_ycgj',pswd:'Tch123456',mobile:phone,msg:'亲，我们很高兴地通知您，'+req.body.myphone+'给您的发车单报价'+price+'元，如果满意，请进入 http://www.iyunche.cn 接受报价。'
                    ,needstatus:true}},
            function optionalCallback(err, httpResponse, body) {
                res.send(true);
            }
        );
    }
});
/*我的订单*/
router.post('/myorders', function(req ,res){
  /*var orders = [{
    startstation:'郑州市 金水区'
    ,endstation:'北京市 涧西区'
    ,starttime:'2015-05-05'
    ,endtime:Date()
    ,status:2
    ,price:5000
    ,contact:'网小姐'
    ,phone:'1234567891'
    ,note:'总共运3种型号10辆车'
  }];
  res.send({
    rows:orders
    ,total:1
  });*/
  //var uid = req.session.passport.user.id || 1;
  var params = {
    uid:req.user.id
    ,page:Number(req.body.page || 1)
    ,rows:Number(req.body.rows || 10)
    ,order:req.body.order || 'createtime'
    ,sort:req.body.sort || 'desc'
    ,status:Number(req.body.status || 2)
    //,advicestate:Number(req.body.advicestate || 0)
  }
  OrderDao.myOrders(params ,function(err ,data){
    if(err){
      res.send({err:'err'})
    }else{
        data.userid = req.user.id;
      res.send(data);
    }
  })

})

//订单详情
router.post('/orderdetail' ,function(req ,res){
  var id = Number(req.body.id);
  OrderDao.orderDetail({id:id} ,function(err ,data){
    if(err){
      res.send({err:'err'})
    }else{
      res.send(data);
    }
  })
})

//取消订单
router.post('/cancelorder' ,function(req ,res){
    OrderDao.cancelOrder(Number(req.body.id) ,function(err ,data){
        if(err){
            res.send({err:'err'});
        }else{
            res.send({status:'success'})
        }
    })
})

//服务评价
router.post('/comment' ,function(req ,res){
  /*var comment={
    inforid:Number(req.body.inforid)
    ,userid:Number(req.body.userid)
    ,carrierid:Number(req.body.carrierid)
    ,attitude:Number(req.body.attitude)
  }*/
  var comment = JSON.parse(req.body.commentJSON);
  comment.createtime = new Date();
  OrderDao.saveComment(comment ,function(err ,data){
    if(err){
      res.send({err:'err'});
    }else{
      res.send({status:'success'})
    }
  })
})

//提交建议
router.post('/suggest' ,function(req ,res){
    var suggest = JSON.parse(req.body.suggestJSON);
    suggest.createtime = new Date();
    OrderDao.saveSuggest(suggest ,function(err ,data){
        if(err){
            res.send({err:'err'});
        }else{
            res.send({status:'success'})
        }
    })
})

//用户认证
router.post('/auth' ,function(req ,res){
    var path1 = './public/image/uploads/';
    var path2 = './public/image/userimg/userid/';
    var idFile = req.files.idcard.name;
    var auth = {
        id:Number(req.body.id)
        ,authstate:2
        ,name:req.body.name
        ,idcard:req.body.idnum
        ,idCardPath:newFile
    }
    var newFile = 'userid-'+auth.id+'.png';
    auth.idCardPath = newFile;
    fs.renameSync(path1+idFile, path2+newFile);
    OrderDao.updateUserInfo(auth ,function(err ,data){
        if(err){
            res.send({err:'err'})
        }else{
            res.send({status:'success'})
        }
    })
})

//修改个人信息
router.post('/modifyinfo' ,function(req ,res){
    OrderDao.updateUserInfo(JSON.parse(req.body.infoJSON) ,function(err ,data){
        if(err){
            res.send({err:'err'})
        }else{
            res.send({status:'success'})
        }
    })
})

//修改头像
router.post('/uploadHeaderFiles' ,function(req ,res){
    var user = req.user;
    var oldFace = user.headerpath;
    var offsetX = Number(req.body.scale1);
    var offsetY = Number(req.body.scale2);
    var width = Number(req.body.width);
    var height = Number(req.body.height);
    var fileName = req.files.files.name;
    //var newFile = 'face-'+user.id+'.png';
    var path1 = './public/image/uploads/';
    var path2 = './public/image/userimg/userface/';

    gm(path1+fileName).crop(width, height, offsetX, offsetY)
        .resize(420, 420)//强制此宽高缩放，不是1比1的话会拉伸，不加！号可保持纵横比
        .noProfile()
        .write(path2+fileName, function (err) {
            if (!err){
                if(fs.existsSync(path1+fileName)){
                    console.log('存在aa');
                    fs.unlinkSync(path1+fileName);//删除文件原
                }

                if(fs.existsSync(path2+oldFace)){
                    console.log('存在xx');
                    fs.unlinkSync(path2+oldFace);
                }
            }
        });

    var value = {
        id:user.id
        ,headerpath:fileName
    }
    OrderDao.updateUserInfo(value ,function(err ,data){
        if(err){
            res.send({err:'err'})
        }else{
            res.send(fileName)
        }
    })
})

//承运方报价
router.post('/mybid' ,function(req ,res){
    var params = {
        //carrierid:Number(req.body.cid)
        carrierid:req.user.id
        ,page:Number(req.body.page)
        ,rows:Number(req.body.rows)
    }
    OrderDao.myBid(params ,function(err ,data){
        if(err){
            res.send({err:'err'})
        }else{
            data.userid = req.user.id;
            res.send(data)
        }
    })
})

//承运方订单
router.post('/carrierorders' ,function(req ,res){
    var params = {
        //carrierid:Number(req.body.cid)
        carrierid:req.user.id
        ,status:Number(req.body.status)
        ,page:Number(req.body.page)
        ,rows:Number(req.body.rows)
    }
    OrderDao.carrierOrders(params ,function(err ,data){
        if(err){
            res.send({err:'err'})
        }else{
            data.userid = req.user.id;
            res.send(data)
        }
    })
})

//承运方订单详情
router.post('/carrierorderdetail' ,function(req ,res){
    var id = Number(req.body.id);
    OrderDao.carrierOrderDetail({id:id} ,function(err ,data){
        if(err){
            res.send({err:'err'})
        }else{
            res.send(data);
        }
    })
})

//承运方认证
router.post('/carrierauth' ,function(req ,res){
    var id = Number(req.body.id)
    var path1 = './public/image/uploads/';
    var path2 = './public/image/userimg/userid/';
    var idFile = req.files.licences.name;
    var newFile = 'licences-'+id+'.png';
    var idFile1 = req.files.roadlicences.name;
    var newFile1 = 'roadlicences-'+id+'.png';
    var auth = {
        id:id
        ,authstate:2
        ,company:req.body.company
        ,contact:req.body.contact
        ,contactnum:req.body.contactnum
        ,licences:newFile
        ,roadlicences:newFile1
    }
    fs.renameSync(path1+idFile, path2+newFile);
    fs.renameSync(path1+idFile1, path2+newFile1);
    OrderDao.updateUserInfo(auth ,function(err ,data){
        if(err){
            res.send({err:'err'})
        }else{
            res.send({status:'success'})
        }
    })
})

/**
 * 获取用户认证状态
 */
router.post('/getAuthState' ,function(req ,res){
    var id = Number(req.body.id);
    new Users().getAuthState(id,Number(req.body.type),function(err ,data){
        if(err){
            res.send({err:'err'})
        }else{
            res.send(data);
        }
    })
});

module.exports = router;
